package infolayer2.graph;

import java.util.Iterator;
import java.util.Map;

import com.google.common.collect.Maps;

public class Graph implements Iterable<Node> {

  Map<String,Node> entities = Maps.newHashMap();
  
  public Node get(String id) {
    return entities.get(id);
  }
  
  public Node create(String id) {
    if (entities.containsKey(id)) {
      throw new IllegalStateException("ID '" + id + "' exists already.");
    }
    Node entity = new Node(id);
    entities.put(id, entity);
    return entity;
  }

  public Node getOrCreate(String id) {
    Node entity = entities.get(id);
    if (entity == null) {
      entity = new Node(id);
      entities.put(id, entity);
    }
    return entity;
  }

  @Override
  public Iterator<Node> iterator() {
    return entities.values().iterator();
  }

  public Node getExpectedType(String propertyId) {
    Node property = entities.get(propertyId);
    if (property != null) {
      Iterator<Edge> it = property.get("/type/property/expected_type").iterator();
      if (it.hasNext()) {
        return get(it.next().getTo());
      }
    }
    return null;
  }
}
